package sng.modules.view.components.city.logic.unit
{
	import as3isolib.geom.Pt;
	
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	import sng.data.info.BuildingInfo;
	import sng.modules.model.vo.BuildingVO;
	import sng.modules.model.vo.UserBuildingVO;
	import sng.modules.view.components.city.cursor.CityCursor;
	import sng.modules.view.components.city.cursor.CityCursorManager;
	import sng.modules.view.components.city.logic.City;
	import sng.modules.view.components.city.logic.CityView;
	import sng.modules.view.components.city.state.CityNewState;
	import sng.modules.view.components.city.state.EnumBuildState;
	import sng.modules.view.components.city.strategy.CityStrategyManage;
	import sng.utils.BuildingUtil;
	import sng.utils.FilterUtil;
	import sng.utils.IsoUtil;
	
	/**
	 * 控制建筑的移动
	 */
	public class DragManager
	{
		
		private var _proxy:Sprite;
		private var view:CityView;//地图
		private var buildingBitmapData:BitmapData;
		private var currX:int;
		private var currY:int;
		private var vo:BuildingVO;
		private var uvo:UserBuildingVO;
		private var swf:SwfSheet;
		private var isExpand:Boolean = false; //是否是扩路操作
		
		private var _proxyBuilding:BaseBuilding;	//代理建筑类
		
		private var icon:IdleIcon	//闲置图标
		private var sideArr:Array;
		private var idleArr:Array;
		
		
		public function drag(_vo:BuildingVO, _view:CityView, _uvo:UserBuildingVO=null):void
		{
			vo = _vo;
			view = _view;
			uvo = _uvo;
			//var frame:Object = Directions.N;
			isExpand = false;
			if(vo.buildingid == 13)//TODO 判断为扩地
			{
				isExpand = true;
			}
			
			_proxyBuilding = new BaseBuilding( uvo!=null?uvo:BuildingInfo.getUserBuildingVOFromTemplateId(vo.buildingid),view,null,null);
			_proxyBuilding.skin.alpha = 0.5;
			//_proxyBuilding.skin.y = Math.ceil(vo.cols/2)*City.GRID_CELLSIZE;
			_proxyBuilding.skin.mouseChildren = false;
			_proxyBuilding.skin.mouseEnabled = false;
			_proxy = new Sprite();
			
			//修正初始坐标 eason 20110713
			icon=new IdleIcon();
			if(vo.buildingTypeId==BuildingUtil.ROAD_TYPE)
			{
				idleArr=new Array();
			}
			onProxyEnterFrame(null);
			
			for each(var s:Sprite in _proxyBuilding.sprites)
			{
				//不将idle放入_proxy中 eaosn 20110720
				if(s is IdleIcon)
					continue;
				s.y+= Math.ceil(vo.cols/2)*City.GRID_CELLSIZE;
				_proxy.addChild(s);
			}
			_view.addChild(_proxy);
			
			//添加鼠标移动事件,比舞台播放事件节省性能,edit by royjin 20110712
			_view.addEventListener(MouseEvent.MOUSE_MOVE, onProxyEnterFrame);
			_view.addEventListener(MouseEvent.MOUSE_UP, drop);
		}
		
		private function onProxyEnterFrame(e:MouseEvent):void
		{
			//TODO 拖动操作时进行城市缩放操作的处理,后续看是否有效率高的处理办法
			if (_proxy != null)
			{
				//设置放大倍数
				_proxy.scaleX = _proxy.scaleY = view.currentZoom;
				//TODO 粘附的具体细节还需调整，如根据地图拖动的位置，地图的缩放尺寸调整。几个变量的计算定义可以考虑放在外部
				
				//获取当前鼠标位置在ISO里的位置
				var p:Point = new Point(view.mouseX, view.mouseY);
				var pt:Pt = view.localToIso(p);

				//获取新的目标在ISO的格子位置	edit by royjin 20110712
				var newCurrX:int = Math.round(pt.x/City.GRID_CELLSIZE);
				var newCurrY:int = Math.round(pt.y/City.GRID_CELLSIZE);
				//如果X和Y任何一个位置于老的不一样才做逻辑操作,节省性能 edit by royjin 20110712
				if(currX!=newCurrX||currY!=newCurrY)
				{
					//trace("x:"+newCurrX+",y:"+newCurrY);
					if(vo.buildingTypeId==BuildingUtil.ROAD_TYPE)
					{
						this.view.city.roadManager.DelPreViewRoad();
					}
					
					currX = newCurrX;
					currY = newCurrY;
					
					pt.x = currX*City.GRID_CELLSIZE;
					pt.y = currY*City.GRID_CELLSIZE;
					
					var currPoint:Point;
					currPoint = view.isoToLocal(pt);
					
					_proxy.x = currPoint.x;
					_proxy.y = currPoint.y;
					_proxyBuilding.column = currX+1;		//不一定
					_proxyBuilding.row = currY+1;			//不一定
					//trace(currPoint.x,currPoint.y);
					var buildAble:Boolean;
					if(isExpand)
					{
						buildAble = IsoUtil.getBuildAbleExpand(City.buildingTypeArray, currX, currY, vo.rows, vo.cols);
					}else{
						buildAble = IsoUtil.getBuildAble(City.buildingTypeArray, currX, currY, vo.rows, vo.cols);
					}
					//					trace("[7,14]",City.buildingTypeArray.get(7,14));
					//					trace("[7,13]",City.buildingTypeArray.get(7,14));
					//					trace("[7,12]",City.buildingTypeArray.get(7,14));
					//					trace("[8,14]",City.buildingTypeArray.get(7,14));
					//					trace("[8,13]",City.buildingTypeArray.get(7,14));
					//					trace("[8,12]",City.buildingTypeArray.get(7,14));
					//					trace("[9,14]",City.buildingTypeArray.get(7,14));
					//					trace("[9,13]",City.buildingTypeArray.get(7,14));
					//					trace("[9,12]",City.buildingTypeArray.get(7,14));
					if(buildAble)
					{
						_proxy.filters = [FilterUtil.getGreenFilter()];
						//更改指针 eason 20110714
						if(CityCursorManager.getInstance().currentCursorType()!=CityCursor.MOVE_CURSOR)
							CityCursorManager.getInstance().setCursor(CityCursor.MOVE_CURSOR);
						
					}else{
						_proxy.filters = [FilterUtil.getRedFilter()];
						//更改指针 eason 20110714
						if(CityCursorManager.getInstance().currentCursorType()==CityCursor.MOVE_CURSOR)
							CityCursorManager.getInstance().setCursor(CityCursor.BUILD_DISENABLE_CURSOR);
					}
					//trace(IsoUtil.getRoadLinkable(City.buildingArray, currX, currY, vo.rows, vo.cols));
					
					//如果是道路,添加预览 edit by royjin 20110712
					if(vo.buildingTypeId==BuildingUtil.ROAD_TYPE&&buildAble==true)
					{
						this.view.city.roadManager.AddPreViewRoad(_proxyBuilding);
					}
						//如果是装饰物 edit by royjin 20110715
					else if(vo.buildingTypeId==BuildingUtil.DECORATION_TYPE)
					{
						BuildingBonusAddManager.UpdateBuildingBonus(_proxyBuilding);
					}
					this._proxyBuilding.ShowGroundSkin();
					//trace("type:"+vo.buildingTypeId+",buildAble:"+buildAble+",IsLink:"+IsoUtil.getRoadLinkable(City.buildingTypeArray, currX-1, currY-1, vo.rows, vo.cols)+",x:"+currX+",y:"+currY);
					
					//判断商业建筑是否连着路 eason 20110720
					checkBuildingIdle();
				}
			}
			
		}
		
		private function checkBuildingIdle():void
		{
			//换算为以底角为中心坐标
			var centerPoint:Point;
			var centerPt:Pt;
			var x:int;
			var y:int;
			var flag:Boolean=false;
			var id:String
			if(vo.buildingTypeId==BuildingUtil.HOUSE_TYPE||vo.buildingTypeId==BuildingUtil.BUSINESS_TYPE)
			{
				//换算为以底角为中心坐标
				centerPoint= new Point(view.mouseX, view.mouseY+Math.ceil(vo.cols/2)*City.GRID_CELLSIZE);
				centerPt= view.localToIso(centerPoint);
				x = Math.round(centerPt.x/City.GRID_CELLSIZE);
				y= Math.round(centerPt.y/City.GRID_CELLSIZE);
				sideArr=IsoUtil.getBuildSideIdArray(x,y,vo.rows, vo.cols);
				for each(id in sideArr)
				{
					if(view.getChildByID(id).vo.buildingTypeId==BuildingUtil.ROAD_TYPE)
					{
						flag=true;
						break;
					}
				}
				if(!flag)
				{
					trace("没连着路");
					if(!_proxy.contains(icon))
					{
						icon.x = 30;
						icon.y = -40+Math.ceil(vo.cols/2)*City.GRID_CELLSIZE;
						_proxy.addChild(icon);
					}
				}
				else
				{
					trace("连着路")
					if(_proxy.contains(icon))
					{
						_proxy.removeChild(icon);
					}
				}
			}
			else if(vo.buildingTypeId==BuildingUtil.ROAD_TYPE)
			{
				//换算为以底角为中心坐标
				centerPoint= new Point(view.mouseX, view.mouseY+Math.ceil(vo.cols/2)*City.GRID_CELLSIZE);
				centerPt= view.localToIso(centerPoint);
				x = Math.round(centerPt.x/City.GRID_CELLSIZE);
				y= Math.round(centerPt.y/City.GRID_CELLSIZE);
//				var tempArr:Array=idleArr.concat();
				sideArr=IsoUtil.getBuildSideIdArray(x,y,vo.rows, vo.cols);
				for each(id in idleArr)
				{
					if(sideArr.indexOf(id)==-1)
					{
						view.getChildByID(id).setIdleUI();
						idleArr.splice(idleArr.indexOf(id),1);
					}
				}
				trace(sideArr);
				for each(id in sideArr)
				{
					var building:BaseBuilding=view.getChildByID(id);
					if(building.vo.buildingTypeId==BuildingUtil.BUSINESS_TYPE||building.vo.buildingTypeId==BuildingUtil.HOUSE_TYPE)
					{
						if(building.uVO.buildStep <= building.vo.createStep && building.uVO.buildStep != 0)
							continue;
						trace("商业建筑");
						if(building.uVO.isIdle)
						{
							building.removeTip();
							idleArr.push(id);
						}
					}
				}
			}
		}
		
		private function drop(e:Event = null):void
		{
			if(view.dragStart) return;
			var p:Point = new Point(_proxy.x, _proxy.y);
			p = view.localToIso(p);
			
			//判断是否可建
			var buildAble:Boolean = IsoUtil.getBuildAble(City.buildingTypeArray, currX, currY, vo.rows, vo.cols);
			if(!buildAble) 
				return;
			
			//是否是新建的建筑
			var isNew:Boolean = false;
			if(uvo==null)
			{
				uvo = new UserBuildingVO();
				uvo.templateId = vo.buildingid;
				uvo.buildStep = 1;
				isNew = true;
			}
			
			uvo.x = Math.floor(p.x)/City.GRID_CELLSIZE+Math.ceil(vo.cols/2);
			uvo.y = Math.floor(p.y)/City.GRID_CELLSIZE+Math.ceil(vo.rows/2);
			
			//clean up
			if(!vo.continuingCreate || (vo.continuingCreate && !isNew))
			{
				view.removeChild(_proxy);
				view.removeEventListener(MouseEvent.MOUSE_UP, drop);
				view.removeEventListener(MouseEvent.MOUSE_MOVE, onProxyEnterFrame);
				_proxy = null;
			}
			
			if(isNew)
			{
				view.city.hudVo.userbuildinglist.addItem(uvo);
			}
			
			//执行当前的状态
			view.city.currentState.Execute(uvo);
			
			/**
			 *	更改为单个修改
			 * 	eason 20110713
			 */
			//			//修改当前地图区块的数据
			//			view.city.setCityBuildData();
			
			//			IsoUtil.changeMapDataByBuilding(view.city.currentBuilding,true);
			
//			trace(City.buildingIdArray.dump())
			
			//继续创建，需要把城市状态置为新建
			if(vo.continuingCreate && isNew)
			{
				view.city.setCityState(new CityNewState(view.city));
			}
			//新建建筑时执行建筑策略的创建逻辑
			if(isNew)
				view.city.currentBuilding.currentStrategy.createBuildingStrategy();
			
			if(isNew)
				uvo = null;
			
			
			if(vo.buildingTypeId==BuildingUtil.DECORATION_TYPE)
			{
				BuildingBonusAddManager.ResetBuildingBonus(this._proxyBuilding);
			}
		}
		
		//强制停止操作
		public function stopDrag():void
		{
			if(idleArr!=null)
			{
				var id:String
				for each(id in idleArr)
				{
					if(sideArr.indexOf(id)==-1)
					{
						view.getChildByID(id).setIdleUI();
						idleArr.splice(idleArr.indexOf(id),1);
					}
				}
			}
			if(view!=null && _proxy!=null)
			{
				view.removeChild(_proxy);
				view.removeEventListener(MouseEvent.MOUSE_UP, drop);
			}
			if(_proxy!=null)
			{
				view.removeEventListener(MouseEvent.MOUSE_MOVE, onProxyEnterFrame);
				_proxy = null;
				
				//是否是新建的建筑
				var isNew:Boolean = false;
				if(uvo==null)
				{
					uvo = new UserBuildingVO();
					uvo.templateId = vo.buildingid;
					uvo.buildStep = 1;
					isNew = true;
				}
				//还原格子占用 eason 20110713
				if(!isNew)
				{
					if (view.city.currentBuilding)
					{
						if (view.city.currentBuilding.isDragStart)
						{
							view.city.currentBuilding.EndMove();
							
							CityStrategyManage.setAddBonusRate(view.city.currentBuilding);//增加新地址带来的增益效果影响 
							CityStrategyManage.setIdelBuilds(view.city.currentBuilding,false);
							
						}
					}
				}
				
				if(vo.buildingTypeId==BuildingUtil.DECORATION_TYPE)
				{
					BuildingBonusAddManager.ResetBuildingBonus(this._proxyBuilding);
				}
			}
			uvo = null;
			//			//抛出完成事件 在BaseBuilding的BeginMove中监听 eason 20110713
			//			DragManager.getInstance().dispatchEvent(new DragManagerEvent(DragManagerEvent.DRAG_END));
		}
		
		/**********************************************
		 * SINGLETON CTOR
		 **********************************************/
		
		private static var _instance:DragManager;
		public function DragManager(enf:SingletonEnforcer)
		{
			
		}
		public static function getInstance():DragManager{
			if(_instance == null) _instance = new DragManager(new SingletonEnforcer());
			return _instance;
		}
		
	}
	
}

class SingletonEnforcer{};
